// 全局过滤器
import Store from '@/store/index';
import { $XTrack } from '@/report';
import $utils from '@/utils';
const Tools = {
  /**
   * 用户昵称超过6个字符，超出部分显示...，英文算0.5
   * */
  formatNickname(value = '', length = 6) {
    const name = [];
    let t = 0;
    for (let a = value.length, n = -1, r = 0; r < a; r++) {
      n = value.charCodeAt(r);
      t += n >= 0 && n <= 128 ? 0.5 : 1;
      if (Math.ceil(t) <= length) {
        name.push(value[r]);
      } else {
        name.push('...');
        break;
      }
    }
    return name.join('');
  },
  /**
   * 小数点后补多位0   ==>  12.00000000 || 12.12340000
   * */
  formatZero(number = 0, n = 2) {
    if (isNaN(Number(number))) {
      return '';
    }
    if (n <= 0) {
      return Math.round(number);
    }
    number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n); // 四舍五入
    number = Number(number).toFixed(n); // 补足位数
    return number;
  },
  /**
   * 数据格式化保留小数点   ==>  12,345.12 || 12345.12
   * @param {number} value
   * @param {number} precision 保留小数点
   * @param {boolean} separate 千分位符
   * */
  formatNumber(value = 0, precision = 2, separate = false) {
    const multiple = Math.pow(10, precision);
    if (separate) {
      return (Math.round(Number(value) * multiple) / multiple).toLocaleString();
    } else {
      return Math.round(Number(value) * multiple) / multiple;
    }
  },
  /**
   * formatTimeAgo
   * **/
  formatTimeAgo(time) {
    let date;
    if (typeof time === 'object') {
      date = +new Date(time);
    } else {
      if (typeof time === 'string') {
        if ((/^\d+$/.test(time))) {
          time = parseInt(time);
        } else {
          time = time.replace(/\-/gi, '/');
        }
      }
      date = +new Date(time);
    }
    const between = (+new Date() - date) / 1000;
    if (between < 3600) {
      return `${~~(between / 60)} 分钟前`;
    } else if (between < 86400) {
      return `${~~(between / 3600)} 小时前`;
    } else if (between < (86400 * 365)) {
      return `${~~(between / 86400)} 天前`;
    } else {
      return Tools.formatDate(date, 'MM-dd');
    }
  },
  /**
   * 根据天换算单位
   * **/
  formatDayUnit(day) {
    if (day > 0) {
      if (day % 30 === 0) {
        return `${day / 30}月`;
      } else if (day % 7 === 0) {
        return `${day / 7}周`;
      } else {
        return `${day}天`;
      }
    } else {
      return '';
    }
  },
  /**
   * 根据时间计算时差
   * **/
  formatTimeDiff(start, end) {
    const t = +new Date(end) - +new Date(start);
    return {
      years: Math.floor(t / 1000 / 60 / 60 / 24 / 30 / 12),
      months: Math.floor(t / 1000 / 60 / 60 / 24 / 30),
      day: Math.floor(t / 1000 / 60 / 60 / 24)
    };
  },
  /**
   * 格式化日期
   * */
  formatDate(time, b = 'yyyy-MM-dd hh:mm:ss') {
    if (!arguments.length) {
      return '';
    }
    let date;
    if (typeof time === 'object') {
      date = time;
    } else {
      if (typeof time === 'string') {
        if ((/^\d+$/.test(time))) {
          time = parseInt(time);
        } else {
          time = time.replace(/-/gi, '/');
        }
      }
      if ((typeof time === 'number') && (time.toString().length === 10)) {
        time = time * 1000;
      }
      date = new Date(time);
    }
    const c = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds()
    };
    if (/(y+)/.test(b)) {
      b = b.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }
    for (const a in c) {
      if (new RegExp('(' + a + ')').test(b)) {
        b = b.replace(RegExp.$1, RegExp.$1.length === 1 ? c[a] : ('00' + c[a]).substr(('' + c[a]).length));
      }
    }
    return b;
  },
  /**
   * clean Array
   * */
  cleanArray(actual) {
    const newArray = [];
    for (let i = 0; i < actual.length; i++) {
      if (actual[i]) {
        newArray.push(actual[i]);
      }
    }
    return newArray;
  },
  /**
   * Object to param
   * {a: 1, b: 2} => a=1&b=2
   * json[key]暂不做encodeURIComponent处理，路由跳转时如果有中文等特殊字符，会自动转换一次；避免被转2次的问题。
   * */
  object2param(json) {
    if (!json) return '';
    return this.cleanArray(
      Object.keys(json).map(key => {
        if (!json[key]) return '';
        return key + '=' + encodeURI(json[key]);
      })
    ).join('&');
  },

  /**
   * @param {string} param
   * @returns {Object}
   */
  param2Object(param = '') {
    if (!param || param.length === 0) {
      return {};
    }
    const paramString = decodeURIComponent(param);
    let paramList = [];
    const paramObj = {};
    if (paramString.indexOf('&') >= 0) {
      paramList = paramString.split('&');
    } else {
      paramList[0] = paramString;
    }
    paramList.forEach(value => {
      paramObj[value.split('=')[0]] = decodeURIComponent(value.split('=')[1]);
    });
    return paramObj;
  },
  numberFormat(value) {
    const param = {};
    const k = 10000;
    const sizes = ['', '万', '亿', '万亿'];
    let i;
    if (value < k) {
      param.value = value;
      param.unit = '';
    } else {
      i = Math.floor(Math.log(value) / Math.log(k));

      param.value = ((value / Math.pow(k, i))).toFixed(1);
      param.unit = sizes[i];
    }
    return param.value + param.unit;
  },
  /**
   * 格式化大数值及单位  1234567 => 1百万
   * **/
  formatCount(param) {
    let object = {
      count: 0,
      unit: [[4, '万'], [5, '十万'], [6, '百万'], [7, '千万'], [8, '亿']],
      suffix: ''
    };
    if (typeof param === 'object') {
      object = Object.assign(object, param);
    } else if (typeof param === 'number') {
      object.count = param;
    }
    const UNIT_ARRAY = object.unit;
    let result = '';

    if (object.count > 0) {
      const len = String(object.count).length - 1;
      const findIndex = UNIT_ARRAY.findIndex(item => item[0] === len);
      if (findIndex !== -1) {
        const val = this.formatNumber(object.count / Math.pow(10, UNIT_ARRAY[findIndex][0]), 1);
        result = val + UNIT_ARRAY[findIndex][1];
      } else {
        result = object.count;
      }
    } else {
      result = 0;
    }
    return result + object.suffix;
  },
  // 复制
  setClipboardData(data, target) {
    uni.setClipboardData({
      data,
      success: () => {
        uni.showToast({
          title: '复制成功~',
          icon: 'none'
        });
      }
    });
  },
  // 手机号码加星号
  encryptMobile(val) {
    return val.substr(0, 3) + '****' + val.substr(7);
  },
  // 字典变数据过滤器
  dictionary(value, key) {
    const map = Store.getters.dictionary[key];
    if (map) {
      const res = map.filter(v => String(v.value) === String(value));
      return res[0] ? res[0].label : '';
    }
  },
  // 格式化首页、微页面、聚合页数据
  formatPageData(data) {
    data.pageStyle = typeof data.pageStyle === 'string' ? JSON.parse(data.pageStyle) : data.pageStyle;
    if (data.componentList) {
      // 解析componentStyle
      data.componentList.forEach(item => {
        item.componentStyle = typeof item.componentStyle === 'string' ? JSON.parse(item.componentStyle) : item.componentStyle;

        // 解析contentStyle
        item.componentContentList.forEach(contentItem => {
          contentItem.contentStyle = typeof contentItem.contentStyle === 'string' ? JSON.parse(contentItem.contentStyle) : contentItem.contentStyle;
        });
      });

      const allListIndex = data.componentList.findIndex(item => item.type === 7);
      if (allListIndex > -1) {
        const allList = data.componentList.splice(allListIndex, 1);
        data.componentList.push(allList[0]);
      }
    }
    return data;
  },
  /**
   * 格式化cdn图片地址 cdn.madaomall.com = cdn.madaomall.com ?x-oss-process=image/quality,q_75/format,webp
   * @param {string} url 图片地址
   * @param {number} w 尺寸
   * @param {number} q 质量
   * */
  formatOss(url, w = 640, q = 85) {
    // 马到的CDN地址格式化
    const windowInfo = uni.getWindowInfo();
    const deviceInfo = uni.getDeviceInfo ? (uni.getDeviceInfo() || {}) : {};
    const oss = ['?x-oss-process=image'];
    if (url && (!/\?/gi.test(url) || url.includes('?width='))) {
      let src = url;
      if (url.includes('?width=')) {
        // url中带图片宽高信息的处理逻辑
        src = url.split('?')[0];
      }
      // 宽度与质量处理
      if (windowInfo.pixelRatio <= 1) {
        oss.push(`resize,w_${parseInt(w / 2, 10)}`);
        oss.push(`quality,q_${parseInt(q * 1.1, 10)}`);
      } else {
        oss.push(`resize,w_${w}`);
        oss.push(`quality,q_${q}`);
      }

      // 图片格式
      if (/.gif$/gi.test(src)) {
        oss.push('format,gif');
      } else {
        if (/ios/gi.test(deviceInfo.system)) {
          oss.push('format,jpg');
        } else {
          oss.push('format,webp');
        }
      }
      return [src, oss.join('/')].join('');
    } else {
      return url;
    }
  },
  /**
   * 根据字符串生成hash数
   * @param {string} str 参数
   * **/
  hashCode(str) {
    let hash = 0; let i; let chr; let len;
    if (str.length === 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
      chr = str.charCodeAt(i);
      hash = ((hash << 5) - hash) + chr;
      hash |= 0; // Convert to 32bit integer
    }
    return hash;
  },
  /**
   * 商品列表格式化商品价格
   * **/
  formatPrice(item) {
    if (item.couponType === 1 && (item.subsidyPrice - item.transactionAmount > 0 || item.productPrice - item.transactionAmount > 0)) {
      return item.subsidyPrice ? Tools.formatNumber(item.subsidyPrice - item.couponAmount > 0 ? item.subsidyPrice - item.couponAmount : '0.01')
        : Tools.formatNumber(item.productPrice - item.couponAmount > 0 ? item.productPrice - item.couponAmount : '0.01');
    } else if (item.couponType === 2) {
      return item.subsidyPrice ? Tools.formatNumber(item.subsidyPrice - item.couponAmount > 0 ? item.subsidyPrice - item.couponAmount : '0.01')
        : Tools.formatNumber(item.productPrice - item.couponAmount > 0 ? item.productPrice - item.couponAmount : '0.01');
    } else if (item.subsidyPrice) {
      return item.subsidyPrice;
    } else {
      return item.productPrice;
    }
  },
  /**
   * 换算图片宽高比
   * **/
  convertPicRatio(item) {
    try {
      const windowInfo = uni.getWindowInfo();
      const object = Tools.param2Object(item.split('?')[1]);
      const w = windowInfo.windowWidth;
      const h = parseInt(object.height * (w / object.width), 10);
      return {
        width: `${w}px`,
        height: `${h}px`
      };
    } catch (e) {
      return {};
    }
  },
  /**
   * 格式化联系客服数据
   * **/
  $formatCustomerServiceChat(storeInfo, shareCustomerData, path) {
    const { contactLink, corpId, storeId } = storeInfo || {};
    const { cardKeywords, cardUrl } = shareCustomerData || {};
    let params = {
      storeId,
      corpId
    };
    if (cardKeywords) {
      params = Object.assign(params, {
        showMessageCard: true,
        sendMessageTitle: cardKeywords,
        sendMessageImg: cardUrl,
        sendMessagePath: path
      });
    }
    if (path) {
      params.sendMessagePath = path;
    }

    // 埋点
    $XTrack('OpenCustomerServiceChat', {
      ...params,
      url: contactLink
    });

    // 呼起客服
    $utils.$openCustomerServiceChat(contactLink, params);
  },
  // 格式化sku数据
  formatSku(productSkus) {
    const skuInfo = [];
    const skuList = productSkus.map(sku => {
      const { skuSpec, id, costPrice, skuGroupPrice, thumbImg, skuPrice } = sku;
      const attr = skuSpec.map(item => {
      // 根据完整的sku数据生成简易的规格数据
        const find = skuInfo.find(s => s.name === item.specName);
        if (find) {
          if (!find.value.some(s => s === item.specValue)) {
            find.value.push(item.specValue);
            find.valueInfo.push({
              value: item.specValue,
              recommendedFlag: item.recommendedFlag === 1,
              specPic: item.specPic
            });
          }
        } else {
          skuInfo.push({
            name: item.specName,
            hasSpecPic: !!item.specPic,
            value: [item.specValue],
            selected: item.specValue,
            valueInfo: [{
              value: item.specValue,
              recommendedFlag: item.recommendedFlag === 1,
              specPic: item.specPic
            }]
          });
        }
        return {
          name: item.specName,
          value: item.specValue
        };
      });
      return {
        id,
        costPrice,
        skuGroupPrice,
        attr,
        skuPrice,
        thumbImg
      };
    });
    return {
      skuInfo,
      skuList
    };
  },
  // 匹配最优佳优惠券
  matchBestCoupon(couponList, productPrice) {
    try {
      const canUse = [];
      // 大促金额，一个订单只减一次大促价，不跟数量走
      for (let j = 0; j < couponList.length; j++) {
        // couponType 类型：1-满减券；2-直减券，usableStatus
        const coupon = couponList[j];
        if (coupon.couponType === 2 || productPrice >= coupon.transactionAmount) {
          canUse.push(couponList[j]);
        }
      }
      if (canUse.length > 0) {
        return canUse.sort((a, b) => {
          return b.couponAmount - a.couponAmount;
        })[0];
      } else {
        return null;
      }
    } catch (e) {
      return null;
    }
  }
};
export default Tools;
